package com.smedi.ismedi.notification.core.application.service.impl;

import com.smedi.ismedi.notification.core.application.command.SmsTemplateCommand;
import com.smedi.ismedi.notification.core.application.service.SmsTemplateApplicationService;
import com.smedi.ismedi.notification.core.domain.aggregatemodel.SmsTemplate;
import com.smedi.ismedi.notification.core.domain.service.SmsTemplateDomainService;
import com.smedi.ismedi.notification.core.port.service.SmsClientRemoteApiService;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: xulinjun
 * @Date: 2021-7-11 15:15
 */
@Slf4j
@Service
@AllArgsConstructor
public class SmsTemplateApplicationServiceImpl implements SmsTemplateApplicationService {
    private final DozerUtil dozerUtil;

    private final SmsTemplateDomainService smsTemplateDomainService;

    private final SmsClientRemoteApiService smsClientRemoteApiService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SmsTemplate saveTemplate(SmsTemplateCommand smsTemplateCommand) {
        SmsTemplate smsTemplate = dozerUtil.convertor(smsTemplateCommand, SmsTemplate.class);

        if (smsTemplate.getSmsTemplateId() != null) {
            return updateTemplate((smsTemplate));
        } else {
            return newTemplate(smsTemplate);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTemplate(Long smsTemplateId) {
        Long tencentTemplateId = smsTemplateDomainService.deleteTemplate(smsTemplateId);
        smsClientRemoteApiService.deleteSmsTemplate(tencentTemplateId);
    }

    private SmsTemplate newTemplate(SmsTemplate data) {
        SmsTemplate smsTemplate = smsTemplateDomainService.createTemplate(data);

        // 调用腾讯云获取模板id
        Long tencentTemplateId = smsClientRemoteApiService.addSmsTemplate(smsTemplate);
        smsTemplate.setTencentTemplateId(tencentTemplateId);

        return smsTemplateDomainService.setTencentTemplateId(smsTemplate);
    }

    private SmsTemplate updateTemplate(SmsTemplate data) {
        SmsTemplate smsTemplate = smsTemplateDomainService.updateTemplate(data);

        // 调用腾讯云更新模板
        smsClientRemoteApiService.modifySmsTemplate(smsTemplate);
        return smsTemplate;
    }
}
